'use client';

import * as React from 'react';

import { Check, ChevronsUpDownIcon } from 'lucide-react';

import { cn } from '@/lib/utils';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '@/components/ui/command';
import { Button } from '@/components/ui/button';

// 定义选项数据结构
export interface OptionItem {
  label: string;
  value: number;
}

interface ComboboxProps {
  frameworks: OptionItem[];
  defaultValue?: number;
  value?: number;
  onChange?: (value: number) => void;
}

export function Combobox({ frameworks, defaultValue = 0, value, onChange }: ComboboxProps) {
  const [open, setOpen] = React.useState(false);
  var currentValue = value ?? defaultValue;

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger className="w-full">
        <Button
          type="button"
          variant="outline"
          role="combobox"
          aria-expanded={open}
          className="w-full justify-between"
        >
          {frameworks.find((framework: OptionItem) => framework.value === currentValue)?.label ||
            '未设置选项'}
          <ChevronsUpDownIcon />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-80 h-auto p-4 z-1000 bg-white border rounded-md shadow-lg">
        <Command>
          <CommandInput placeholder="搜索框架" />
          <CommandList>
            <CommandEmpty>没找到相关数据</CommandEmpty>
            <CommandGroup>
              {frameworks.map((framework: OptionItem) => (
                <CommandItem
                  key={framework.value}
                  value={framework.value?.toString() || ''}
                  onSelect={(v) => {
                    onChange?.(Number(v));
                    setOpen(false);
                  }}
                >
                  {framework.label}
                  <Check
                    className={cn(
                      'ml-auto',
                      currentValue === framework.value ? 'opacity-100' : 'opacity-0'
                    )}
                  />
                </CommandItem>
              ))}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
}
